import { ApiCall } from 'tsrpc'
import { ReqGetConfigStats, ResGetConfigStats } from '../shared/api_config_editor/PtlGetConfigStats'
import { ConfigStats } from '../shared/api_config_editor/base'
import { configManager } from '../config/ConfigManager'

export default async function (call: ApiCall<ReqGetConfigStats, ResGetConfigStats>) {
    try {
        // 获取装备统计
        const equipmentStats = configManager.getStats()
        
        // 获取技能统计
        const skillStats = configManager.getSkillStats()
        
        // 计算其他配置文件的统计
        const fs = require('fs')
        const path = require('path')
        const configDir = path.resolve(__dirname, '../core/config')
        
        const configsByType: Record<string, number> = {
            equipment: equipmentStats.totalEquipments,
            skill: skillStats.totalSkills
        }
        
        let totalConfigs = equipmentStats.totalEquipments + skillStats.totalSkills
        let lastModified = Date.now()
        let memoryUsage = '0MB'
        
        // 统计其他配置文件
        if (fs.existsSync(configDir)) {
            const files = fs.readdirSync(configDir)
            const jsonFiles = files.filter((file: string) => file.endsWith('.json'))
            
            for (const file of jsonFiles) {
                try {
                    const fileName = file.replace('.json', '')
                    const parts = fileName.split('_')
                    
                    if (parts.length >= 2) {
                        const configType = parts[0]
                        
                        if (!configsByType[configType]) {
                            const filePath = path.join(configDir, file)
                            const content = fs.readFileSync(filePath, 'utf-8')
                            const data = JSON.parse(content)
                            const count = Array.isArray(data) ? data.length : 1
                            
                            configsByType[configType] = count
                            totalConfigs += count
                            
                            // 更新最后修改时间
                            const stats = fs.statSync(filePath)
                            if (stats.mtime.getTime() > lastModified) {
                                lastModified = stats.mtime.getTime()
                            }
                        }
                    }
                } catch (error) {
                    console.warn(`Failed to read config file ${file}:`, error)
                }
            }
        }
        
        // 计算内存使用情况（粗略估算）
        try {
            const process = require('process')
            const memUsage = process.memoryUsage()
            memoryUsage = `${Math.round(memUsage.heapUsed / 1024 / 1024)}MB`
        } catch (error) {
            // 忽略内存统计错误
        }
        
        // 计算健康状态
        let healthStatus: 'healthy' | 'warning' | 'error' = 'healthy'
        let validationScore = 100
        
        // 基于配置数量和兼容性评估健康状态
        if (totalConfigs === 0) {
            healthStatus = 'error'
            validationScore = 0
        } else if (skillStats.compatibilityScore < 80) {
            healthStatus = 'warning'
            validationScore = skillStats.compatibilityScore
        }
        
        const stats: ConfigStats = {
            totalConfigs,
            configsByType,
            lastModified,
            healthStatus,
            validationScore,
            memoryUsage
        }
        
        call.succ({
            data: stats
        })
        
    } catch (error) {
        console.error('Failed to get config stats:', error)
        call.error('获取配置统计失败', {
            errors: [(error as any).message]
        })
    }
}
